package top.szhome.framework.starter.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import top.szhome.framework.starter.jwt.property.JwtProperties;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * jwt工具类
 *
 * @author 唐加利
 * @date 2023/7/24
 **/
public class JwtUtil {

    /**
     * token标记
     */
    public static String BEARER = "bearer";

    /**
     * token标记长度
     */
    public static Integer AUTH_LENGTH = BEARER.length();

    /**
     * jwt配置
     */
    private static JwtProperties jwtProperties;

    /**
     * JWT工具类构造方法，主要用于设置JwtProperties
     * @param jwtProperties
     */
    public JwtUtil(JwtProperties jwtProperties){
        JwtUtil.jwtProperties = jwtProperties;
    }

    /**
     * 获取请求传递的token串
     *
     * @param auth token
     * @return String
     */
    public static String getToken(String auth) {
        if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
            String headStr = auth.substring(0, AUTH_LENGTH).toLowerCase();
            if (headStr.compareTo(BEARER) == 0) {
                // 加一个空格
                auth = auth.substring(AUTH_LENGTH + 1);
            }
            return auth;
        }

        return null;
    }

    /**
     * 解析jsonWebToken
     *
     * @param jsonWebToken token串
     * @return Claims
     */
    public static Claims parseJWT(String jsonWebToken) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(Base64.getDecoder().decode(getBase64Security())).build()
                    .parseClaimsJws(jsonWebToken).getBody();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 签名加密
     */
    public static String getBase64Security() {
        return Base64.getEncoder().encodeToString(jwtProperties.getSignKey().getBytes(StandardCharsets.UTF_8));
    }

}
